package com.shanjupay.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 *
 */
@Slf4j
@Service
public class SmsServiceImpl  implements SmsService {

    private static final String SMS_SEND_URI = "/generate" ;
    private static final String SMS_VERIFIY_URI = "/verify" ;

    private static final String SMS_SEND_URL = SMS_SEND_URI ;

    @Value("${sms.url}")
    private String url ;


    @Value("${sms.effectiveTime}")
    private int effectiveTime ;

    @Autowired
    private RestTemplate restTemplate;



    @Override
    public String sendMsg(String phone) {

        String urlParams = url + SMS_SEND_URL+"?name=sms&effectiveTime="+ effectiveTime;

        // 请求信息
        // 请求头信息
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        // 请求body体
        Map<String,Object> body = new HashMap<>();
        body.put("mobile",phone);

        // 请求信息，传入body, header
        HttpEntity httpEntity = new HttpEntity(body,httpHeaders);

        ResponseEntity<Map> exchange = null ;

        Map responseMap;

        try {
             exchange = restTemplate.exchange(urlParams, HttpMethod.POST, httpEntity, Map.class);
             log.info("调用短信微服务发送短信验证码：返回值：{}", JSON.toJSONString(exchange));
            responseMap = exchange.getBody();
        }catch (Exception exception){
            exception.printStackTrace();
            throw new RuntimeException("发送验证码失败!");
        }

        if(responseMap == null || responseMap.get("result") == null){
            throw new RuntimeException("发送验证码出错");
        }

        Map resultMap = (Map) responseMap.get("result");

        String key = resultMap.get("key").toString();
        log.info("得到发送验证码对应的key:{}",key);
        return key;
    }

    @Override
    public void checkVerifiyCode(String verifiyKey, String verifiyCode) throws BusinessException {
        //实现校验验证码的逻辑

        String  smsVerifiyUrl = url + SMS_VERIFIY_URI+ "?name=sms&verificationCode="+verifiyCode+"&verificationKey="+verifiyKey ;
        Map responseMap = null ;

        try {
            // 请求校验验证码
            ResponseEntity<Map> exchange = restTemplate.exchange(smsVerifiyUrl, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
            log.info("调用短信微服务校验短信验证码：返回值：{}", JSON.toJSONString(exchange));
            responseMap = exchange.getBody();
        }catch (Exception exception){
            exception.printStackTrace();
            // throw new RuntimeException("校验验证码失败!");
            throw new BusinessException(CommonErrorCode.E_100102);
        }

        if(responseMap == null || responseMap.get("result") == null || !(Boolean) responseMap.get("result")){
           // throw new RuntimeException("校验验证码失败!");
            throw new BusinessException(CommonErrorCode.E_100102);
        }

    }
}
